import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';

class TimeController extends GetxController
    implements VideoInteractionObserver, VideoDeleteObserver {
  TimeController();

  // 仓库
  final RecommendedVideoRepository _videoRepository =
      RecommendedVideoRepository();
  final VideoInteractionRepository _videoInteractionRepository =
      VideoInteractionRepository();
  final BrowseRecordRepository _browseRecordRepository =
      BrowseRecordRepository();

  // 推荐视频列表
  final RxList<RecommendedVideo> recommendedVideos = <RecommendedVideo>[].obs;

  // 当前选择的视频索引
  final RxInt currentVideoIndex = 0.obs;

  // 视频是否已被点赞/收藏 (用于当前选中的视频)
  final RxBool isLiked = false.obs;
  final RxBool isFavorited = false.obs;

  // 每个视频的点赞/收藏状态
  final RxMap<int, bool> videoLikeStatus = <int, bool>{}.obs;
  final RxMap<int, bool> videoFavoriteStatus = <int, bool>{}.obs;

  // 浏览用户数据
  final RxMap<int, RxList<User>> videoViewedUsers = <int, RxList<User>>{}.obs;
  final RxMap<int, RxBool> videoUsersLoading = <int, RxBool>{}.obs;

  // 获取当前登录用户ID
  int get currentUserId {
    final userService = Get.find<UserService>();
    return userService.currentUser.value?.id ?? -1;
  }

  // 初始化数据
  _initData() async {
    await loadRecommendedVideos();
    update(["time"]);
  }

  // 加载推荐视频数据
  Future<void> loadRecommendedVideos() async {
    try {
      final videos = await _videoRepository.getAllRecommendedVideos();

      recommendedVideos.value = videos;
      // 默认选择第一个视频
      currentVideoIndex.value = 0;

      // 加载每个视频的交互状态
      await loadAllVideosInteractionStatus();

      // 加载每个视频的浏览用户
      for (var video in videos) {
        if (video.id != null) {
          loadVideoViewedUsers(video.id!);
        }
      }
    } catch (e) {
      print('加载推荐视频失败: $e');
    }
  }

  // 加载所有视频的交互状态
  Future<void> loadAllVideosInteractionStatus() async {
    // 如果用户未登录，则不检查交互状态
    if (currentUserId < 0) {
      return;
    }

    for (var video in recommendedVideos) {
      if (video.id != null) {
        // 加载点赞状态
        final isLiked = await _videoInteractionRepository.hasLiked(
          currentUserId,
          video.id!,
        );
        videoLikeStatus[video.id!] = isLiked;

        // 加载收藏状态
        final isFavorited = await _videoInteractionRepository.hasFavorited(
          currentUserId,
          video.id!,
        );
        videoFavoriteStatus[video.id!] = isFavorited;
      }
    }

    // 同时更新当前选中视频的状态
    await checkInteractions();
  }

  // 加载视频浏览用户
  Future<void> loadVideoViewedUsers(int videoId) async {
    // 初始化loading状态
    if (!videoUsersLoading.containsKey(videoId)) {
      videoUsersLoading[videoId] = false.obs;
    }

    // 避免重复加载
    if (videoUsersLoading[videoId]!.value) return;

    videoUsersLoading[videoId]!.value = true;

    try {
      final users = await _browseRecordRepository.getViewedUsersByContent(
        videoId,
        BrowseType.video,
        limit: 4,
      );

      if (!videoViewedUsers.containsKey(videoId)) {
        videoViewedUsers[videoId] = <User>[].obs;
      }

      videoViewedUsers[videoId]!.value = users;
    } catch (e) {
      print('加载视频浏览用户失败: $e');
    } finally {
      videoUsersLoading[videoId]!.value = false;
    }
  }

  // 获取视频的浏览用户
  List<User> getVideoViewedUsers(int videoId) {
    if (!videoViewedUsers.containsKey(videoId)) {
      return [];
    }
    return videoViewedUsers[videoId]!;
  }

  // 判断视频浏览用户是否加载中
  bool isVideoUsersLoading(int videoId) {
    if (!videoUsersLoading.containsKey(videoId)) {
      return false;
    }
    return videoUsersLoading[videoId]!.value;
  }

  // 检查当前视频是否已被点赞/收藏
  Future<void> checkInteractions() async {
    // 如果用户未登录，则不检查交互状态
    if (currentUserId < 0) {
      isLiked.value = false;
      isFavorited.value = false;
      return;
    }

    final currentVideo = getCurrentVideo();
    if (currentVideo?.id != null) {
      // 优先使用已缓存的状态
      if (videoLikeStatus.containsKey(currentVideo!.id!)) {
        isLiked.value = videoLikeStatus[currentVideo.id!]!;
      } else {
        // 如果没有缓存，则从仓库获取
        isLiked.value = await _videoInteractionRepository.hasLiked(
          currentUserId,
          currentVideo.id!,
        );
        videoLikeStatus[currentVideo.id!] = isLiked.value;
      }

      if (videoFavoriteStatus.containsKey(currentVideo.id!)) {
        isFavorited.value = videoFavoriteStatus[currentVideo.id!]!;
      } else {
        isFavorited.value = await _videoInteractionRepository.hasFavorited(
          currentUserId,
          currentVideo.id!,
        );
        videoFavoriteStatus[currentVideo.id!] = isFavorited.value;
      }

      debugPrint(
        '检查交互状态: 视频ID=${currentVideo.id}, 用户ID=$currentUserId, 已点赞=${isLiked.value}, 已收藏=${isFavorited.value}',
      );
    }
  }

  // 获取视频的点赞状态
  bool isVideoLiked(int videoId) {
    return videoLikeStatus[videoId] ?? false;
  }

  // 获取视频的收藏状态
  bool isVideoFavorited(int videoId) {
    return videoFavoriteStatus[videoId] ?? false;
  }

  // 获取当前选中的视频
  RecommendedVideo? getCurrentVideo() {
    if (recommendedVideos.isEmpty ||
        currentVideoIndex.value >= recommendedVideos.length) {
      return null;
    }
    return recommendedVideos[currentVideoIndex.value];
  }

  // 选择视频
  Future<void> selectVideo(int index) async {
    if (index >= 0 && index < recommendedVideos.length) {
      currentVideoIndex.value = index;
      await checkInteractions();
      update(["time"]);
    }
  }

  // 点赞/取消点赞视频
  Future<void> toggleLike() async {
    // 检查用户是否登录
    if (currentUserId < 0) {
      return;
    }

    final currentVideo = getCurrentVideo();
    if (currentVideo?.id == null) return;

    try {
      if (isLiked.value) {
        // 取消点赞
        final success = await _videoInteractionRepository.unlikeVideo(
          currentUserId,
          currentVideo!.id!,
        );

        if (success) {
          // 更新状态
          isLiked.value = false;
          videoLikeStatus[currentVideo.id!] = false;

          // 直接更新当前视频的计数
          final index = currentVideoIndex.value;
          if (index >= 0 && index < recommendedVideos.length) {
            recommendedVideos[index] = recommendedVideos[index].copyWith(
              likeCount: recommendedVideos[index].likeCount - 1,
            );
          }
        }
      } else {
        // 点赞
        final success = await _videoInteractionRepository.likeVideo(
          currentUserId,
          currentVideo!.id!,
        );

        if (success) {
          // 更新状态
          isLiked.value = true;
          videoLikeStatus[currentVideo.id!] = true;

          // 直接更新当前视频的计数
          final index = currentVideoIndex.value;
          if (index >= 0 && index < recommendedVideos.length) {
            recommendedVideos[index] = recommendedVideos[index].copyWith(
              likeCount: recommendedVideos[index].likeCount + 1,
            );
          }
        }
      }

      // 通知UI更新
      update(["time"]);
    } catch (e) {
      print('视频点赞操作失败: $e');
    }
  }

  // 收藏/取消收藏视频
  Future<void> toggleFavorite() async {
    // 检查用户是否登录
    if (currentUserId < 0) {
      return;
    }

    final currentVideo = getCurrentVideo();
    if (currentVideo?.id == null) return;

    try {
      if (isFavorited.value) {
        // 取消收藏
        final success = await _videoInteractionRepository.unfavoriteVideo(
          currentUserId,
          currentVideo!.id!,
        );

        if (success) {
          // 更新状态
          isFavorited.value = false;
          videoFavoriteStatus[currentVideo.id!] = false;

          // 直接更新当前视频的计数
          final index = currentVideoIndex.value;
          if (index >= 0 && index < recommendedVideos.length) {
            recommendedVideos[index] = recommendedVideos[index].copyWith(
              favoriteCount: recommendedVideos[index].favoriteCount - 1,
            );
          }
        }
      } else {
        // 收藏
        final success = await _videoInteractionRepository.favoriteVideo(
          currentUserId,
          currentVideo!.id!,
        );

        if (success) {
          // 更新状态
          isFavorited.value = true;
          videoFavoriteStatus[currentVideo.id!] = true;

          // 直接更新当前视频的计数
          final index = currentVideoIndex.value;
          if (index >= 0 && index < recommendedVideos.length) {
            recommendedVideos[index] = recommendedVideos[index].copyWith(
              favoriteCount: recommendedVideos[index].favoriteCount + 1,
            );
          }
        }
      }

      // 通知UI更新
      update(["time"]);
    } catch (e) {
      print('视频收藏操作失败: $e');
    }
  }

  void onTap() {}

  @override
  void onInit() {
    super.onInit();
    // 注册为观察者，接收视频交互状态更新
    VideoInteractionRepository.addObserver(this);
    // 注册为观察者，接收视频删除通知
    RecommendedVideoRepository.addObserver(this);
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    // 取消注册观察者
    VideoInteractionRepository.removeObserver(this);
    RecommendedVideoRepository.removeObserver(this);
    super.onClose();
  }

  // 实现VideoInteractionObserver接口
  @override
  void onVideoLikeStatusChanged(int userId, int videoId, bool isLiked) {
    // 更新视频的点赞状态
    videoLikeStatus[videoId] = isLiked;

    // 如果当前视频与状态变更的视频是同一个，则更新状态
    final currentVideo = getCurrentVideo();
    if (currentVideo?.id == videoId) {
      this.isLiked.value = isLiked;
    }

    // 更新视频列表中相应视频的点赞数
    for (int i = 0; i < recommendedVideos.length; i++) {
      if (recommendedVideos[i].id == videoId) {
        recommendedVideos[i] = recommendedVideos[i].copyWith(
          likeCount:
              isLiked
                  ? recommendedVideos[i].likeCount + 1
                  : recommendedVideos[i].likeCount - 1,
        );
      }
    }

    update(["time"]);
  }

  @override
  void onVideoFavoriteStatusChanged(int userId, int videoId, bool isFavorited) {
    // 更新视频的收藏状态
    videoFavoriteStatus[videoId] = isFavorited;

    // 如果当前视频与状态变更的视频是同一个，则更新状态
    final currentVideo = getCurrentVideo();
    if (currentVideo?.id == videoId) {
      this.isFavorited.value = isFavorited;
    }

    // 更新视频列表中相应视频的收藏数
    for (int i = 0; i < recommendedVideos.length; i++) {
      if (recommendedVideos[i].id == videoId) {
        recommendedVideos[i] = recommendedVideos[i].copyWith(
          favoriteCount:
              isFavorited
                  ? recommendedVideos[i].favoriteCount + 1
                  : recommendedVideos[i].favoriteCount - 1,
        );
      }
    }

    update(["time"]);
  }

  // 跳转到视频详情页
  void goToVideoDetail(int index) {
    // 如果传入的索引无效，则使用当前选择的视频索引
    if (index < 0 || index >= recommendedVideos.length) {
      index = currentVideoIndex.value;
    }

    // 记录浏览记录
    final video = recommendedVideos[index];
    if (video.id != null && currentUserId > 0) {
      final record = BrowseRecord(
        userId: currentUserId,
        contentId: video.id!,
        type: BrowseType.video,
        browseTime: DateTime.now(),
      );
      _browseRecordRepository.addBrowseRecord(record);
    }

    // 跳转到视频详情页
    Get.toNamed(
      Routes.videoDetail,
      arguments: {'source': 'all', 'initialIndex': index},
    );
  }

  // 实现VideoDeleteObserver接口
  @override
  void onVideoDeleted(int videoId) {
    // 从推荐视频列表中移除被删除的视频
    int index = recommendedVideos.indexWhere((video) => video.id == videoId);
    if (index != -1) {
      recommendedVideos.removeAt(index);

      // 如果删除的是当前选中的视频，则更新当前索引
      if (index == currentVideoIndex.value) {
        if (recommendedVideos.isEmpty) {
          currentVideoIndex.value = 0;
        } else if (index >= recommendedVideos.length) {
          currentVideoIndex.value = recommendedVideos.length - 1;
        }
        // 否则保持当前索引不变
      } else if (index < currentVideoIndex.value) {
        // 如果删除的视频在当前视频之前，则当前索引需要减1
        currentVideoIndex.value--;
      }

      // 清除该视频的状态缓存
      videoLikeStatus.remove(videoId);
      videoFavoriteStatus.remove(videoId);
      videoViewedUsers.remove(videoId);
      videoUsersLoading.remove(videoId);

      // 更新UI
      update(["time"]);
    }
  }
}
